package com.tunan.system.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tunan.common.PagePermissionUtil;
import com.tunan.common.Result;
import com.tunan.common.resultSub.ResultFailure;
import com.tunan.common.resultSub.ResultSuccess;
import com.tunan.persistence.model.TSysMenu;
import com.tunan.persistence.model.TSysMenuLink;
import com.tunan.system.service.IdentifierGenerator;
import com.tunan.system.service.SysMenuLinkService;
import com.tunan.system.service.SysMenuService;

@Controller
@RequestMapping(value = "SysMenuLink")
public class SysMenuLinkController extends BaseController {
	@Autowired
	private SysMenuLinkService sysMenuLinkService;
	
	@Autowired
	private SysMenuService sysMenuService;

	@Autowired
	private IdentifierGenerator identifierGenerator;
	
	private Logger log = Logger.getLogger(SysMenuLinkController.class);

	@RequestMapping(value = "addMenuLink", method = RequestMethod.GET)
	@ResponseBody
	public TSysMenuLink addMenuLink(String id, HttpServletRequest request) {
		if (StringUtils.isNotBlank(id)) {
			return sysMenuLinkService.selectOne(id);
		}
		return  null;
	}

	@RequestMapping(value = "sysMenuLinkList", method = RequestMethod.GET)
	public ModelAndView sysMenuLinkList(String menuId, HttpServletRequest request) {
		if(StringUtils.isNotBlank(menuId)){
			request.setAttribute("pagePermission", PagePermissionUtil.getPRight(menuId, request.getSession()));
		}
		return new ModelAndView("/system/sysMenuLinkList");
	}

	
	/**
	 * 新增和修改
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Result save(String ids, String rid) {
		ResultSuccess rs = new ResultSuccess();
		ResultFailure rf = new ResultFailure();
		try {
			//先清空所有的权限
			sysMenuLinkService.delete(rid);
			if (StringUtils.isNotBlank(ids)) {
				List<TSysMenuLink> lis = new ArrayList<TSysMenuLink>();
				TSysMenuLink vo = new TSysMenuLink();
				String[] arry = ids.split(",");
				String menid = "";
				String str1 = "";
				String str2 = "";
				String define2 = "";
				String define[] = null;
				String r = "0", w = "0", d = "";
				for (int i = 0; i < arry.length; i++) {
					str1 = arry[i].substring(0, 1);
					str2 = arry[i].substring(1);
					if (str1.equals("d")) {
						define = str2.split("-");
						define2 = define[1];
						str2 = define[0];
					}
					if (!menid.equals("") && !menid.equals(str2)) {
						vo = new TSysMenuLink();
						vo.setId(identifierGenerator.generate());
						vo.setMenuId(menid);
						vo.setR(r);
						vo.setW(w);
						vo.setRoleId(rid);
						vo.setDefined(d);
						lis.add(vo);
						r = "0";
						w = "0";
						d = "";
					}
					if (str1.equals("d")) {
						if(StringUtils.isBlank(d)){
							d = ",";
						}
						d = d + define2 + ",";
					}
					if (str1.equals("r"))
						r = "1";
					if (str1.equals("w"))
						w = "1";
					menid = str2;
				}
				if (!menid.equals("")) {
					vo = new TSysMenuLink();
					vo.setId(identifierGenerator.generate());
					vo.setMenuId(menid);
					vo.setR(r);
					vo.setW(w);
					vo.setRoleId(rid);
					vo.setDefined(d);
					lis.add(vo);
				}
				sysMenuLinkService.batchInsert(lis);
			}
			rs.setMessage("保存成功");
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rf.setMessage("操作失败");
		return rf;
	}
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "loadMenu", method = RequestMethod.GET)
	@ResponseBody
	public List load() {
		List<TSysMenu> list = new ArrayList<TSysMenu>();
		List<Map<String,Object>> lists = new ArrayList<Map<String,Object>>();
		try {
			list = sysMenuService.findByParentMenu("0");
			for (TSysMenu menu : list) {
				String define = menu.getDefineRight();
				String defineStr = "";
				if (null != define && !define.equals("")) {
					String[] arry = define.split(",");
					String[] arry2 = null;
					for (int j = 0; j < arry.length; j++) {
						arry2 = arry[j].split("&");
						if (arry2.length >= 2) {
							defineStr = defineStr + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + arry2[0] + "<input value=\"d"
									+ menu.getId() + "-" + arry2[1] + "\" type=\"checkbox\" style='vertical-align: middle;margin: 0 3px;'>";
						}
					}
				}
				Map<String,Object> maps = new HashMap<String,Object>();
				maps.put("id", menu.getId());
				maps.put("names", menu.getName());
				String readAndWrite ="读<input id='r"+menu.getId()+"' onclick='selectAllMine(0,"+menu.getId()+")' type='checkbox' name='r' value='r"+menu.getId()+"' style='vertical-align: middle;margin: 0 3px;'/>";
				readAndWrite = readAndWrite + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;写<input id='w"+menu.getId()+"' onclick='selectAllMine(1,"+menu.getId()+")' type='checkbox' name='w' value='w"+menu.getId()+"' style='vertical-align: middle;margin: 0 3px;'/>";
				maps.put("readAndWrite", readAndWrite+defineStr);
				maps.put("children", loadMenusByParentId(menu.getId()));
				lists.add(maps);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lists;
	}
	
	/**
	 * 通过一级菜单ID获得其对应的所有子菜单列表
	 * @param parentId
	 * @return
	 * 2015年3月12日
	 * @author cenfuqiang
	 * List
	 */
	@SuppressWarnings({ "rawtypes" })
	private List loadMenusByParentId(String parentId) {
		List lists = new ArrayList();
		List<Map<String,Object>> l = new ArrayList<Map<String,Object>>();
		Map<String,Object> maps = new HashMap<String, Object>();
		List<TSysMenu> list = new ArrayList<TSysMenu>();
		try {
			list = sysMenuService.findByParentMenu(parentId);
			for (TSysMenu menu : list)  {
				maps = new HashMap<String,Object>();
				lists = loadMenusByParentId(menu.getId());
				String define = menu.getDefineRight();
				String defineStr = "";
				if (null != define && !define.equals("")) {
					String[] arry = define.split(",");
					String[] arry2 = null;
					for (int j = 0; j < arry.length; j++) {
						arry2 = arry[j].split("&");
						if (arry2.length >= 2) {
							defineStr = defineStr + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + arry2[0] + "<input value=\"d"
									+ menu.getId() + "-" + arry2[1] + "\" type=\"checkbox\" style='vertical-align: middle;margin: 0 3px;'>";
						}
					}
				}
				if (lists.size() > 0) {
					maps.put("id", menu.getId());
					maps.put("names", menu.getName());
					maps.put("state", "close");
					String readAndWrite ="读<input id='rr"+parentId+"' type='checkbox' name='r' value='r"+menu.getId()+"' style='vertical-align: middle;margin: 0 3px;'/>";
					readAndWrite = readAndWrite + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;写<input id='ww"+parentId+"' type='checkbox' name='w' value='w"+menu.getId()+"' style='vertical-align: middle;margin: 0 3px;'/>";
					maps.put("readAndWrite", readAndWrite+defineStr);
				}
				maps.put("id", menu.getId());
				maps.put("names", menu.getName());
				maps.put("state", "close");
				String readAndWrite ="读<input id='rr"+parentId+"' type='checkbox' name='r' value='r"+menu.getId()+"' style='vertical-align: middle;margin: 0 3px;'/>";
				readAndWrite = readAndWrite + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;写<input id='ww"+parentId+"' type='checkbox' name='w' value='w"+menu.getId()+"' style='vertical-align: middle;margin: 0 3px;'/>";
				maps.put("readAndWrite", readAndWrite+defineStr);
				if (lists.size() > 0) {
					maps.put("children", lists);
				}
				l.add(maps);
			}

		} catch (Exception e) {
			log.error(e);
		}
		return l;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "selectedByRoleId", method = RequestMethod.POST)
	@ResponseBody
	public Result selectedByRoleId(String rid) {
		ResultSuccess rs = new ResultSuccess();
		StringBuffer buf = new StringBuffer();
		try {
			HashMap params = new HashMap();
			params.put("roleId", rid);
			List<TSysMenuLink> list  = sysMenuLinkService.selectAll(params);

			String[] strs = null;
			for (TSysMenuLink role : list) {
				if ("1".equals(role.getR())) {
					buf.append("r" + role.getMenuId()).append(",");
				}
				if ("1".equals(role.getW())) {
					buf.append("w" + role.getMenuId()).append(",");
				}
				if (null != role.getDefined() && !role.getDefined().equals("")) {
					strs = role.getDefined().split(",");
					for (int j = 0; j < strs.length; j++) {
						buf.append("d" + role.getMenuId() + "-" + strs[j]).append(",");
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		rs.setMessage(buf.toString());
		return rs;
	}
}
